package com.example.demo.controller;

import com.example.demo.pojo.Fruit;
import com.example.demo.service.FruitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class FruitController {

    @Autowired
    private FruitService fruitService;

    @GetMapping("/list")
    public String list(Model model){
        List<Fruit> list = fruitService.list();
        model.addAttribute("list",list);
        return "list";
    }

    @GetMapping("/user/{id}")
    public String view(Model model,@PathVariable Integer id){
        Fruit fruit = fruitService.selectById(id);
        model.addAttribute("fruit",fruit);
        return "view";
    }

    @PostMapping("/user")
    public String add(Fruit fruit) {

        Integer result = fruitService.add(fruit);

        return "redirect:list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id, HttpServletRequest request){
        Integer result = fruitService.delete(id);

        // request.getContextPath()  : /demo
        return "redirect:/list";
    }

    @GetMapping("/update/{id}")
    public String toUpdate(Model model,@PathVariable Integer id){
        Fruit fruit = fruitService.selectById(id);
        model.addAttribute("fruit",fruit);
        return "update";
    }

    @PostMapping("/update")
    public String update(Fruit fruit){

        Integer result = fruitService.update(fruit);

        return "redirect:list";
    }
}
